<template>
  <el-dialog
    v-model="dialogVisible"
    title="新增用户"
    width="500"
    :before-close="handleClose"
    draggable
  >
    <el-form
      :model="userInfo"
      :rules="userRules"
      ref="userForm"
      label-width="auto"
      style="max-width: 600px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userInfo.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="userInfo.password"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="userInfo.nickname"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="userInfo.mobile"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="confirm"> Confirm </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
const dialogVisible = ref(false)
const userInfo = ref({})
const userForm = ref(null)
const userRules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
  ],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3|4|5|7|8][0-9]\d{8}$/, message: '手机号格式不正确', trigger: 'blur' }
  ]
})
const open = () => {
  dialogVisible.value = true
}
defineExpose({
  open
})
const emit = defineEmits(['success'])
const confirm = () => {
  userForm.value.validate(async (valid) => {
    if (!valid) {
      ElMessage({ message: '验证未通过', type: 'error' })
      return
    }
    // 验证通过
    console.log(userInfo.value)
    emit('success', userInfo.value)
    dialogVisible.value = false
  })
}
</script>

<style></style>
